// ============================================================================
// 账号管理服务
// ============================================================================

import { WeiboLoginData } from '../../shared/types'
import { ipcService } from './ipc-service'
import { logger } from '@roasmax/logger'

/**
 * 账号管理服务类
 * 封装所有账号相关的操作
 */
class AccountService {
  private serviceLogger = logger

  /**
   * 获取账号列表
   */
  async getAccounts(): Promise<WeiboLoginData[]> {
    try {
      const accounts = await ipcService.invoke<WeiboLoginData[]>('login:get-accounts')
      return accounts || []
    } catch (error) {
      this.serviceLogger.error('获取账号列表失败', error)
      throw error
    }
  }

  /**
   * 开始登录
   */
  async startLogin(): Promise<WeiboLoginData> {
    try {
      const loginData = await ipcService.invoke<WeiboLoginData>('login:start')
      this.serviceLogger.info('登录成功', { userId: loginData.userInfo.id })
      return loginData
    } catch (error) {
      this.serviceLogger.error('登录失败', error)
      throw error
    }
  }

  /**
   * 验证账号会话
   */
  async validateAccount(accountId: string): Promise<boolean> {
    try {
      const result = await ipcService.invoke<{ isValid: boolean; reason?: string; details?: any }>('login:validate', accountId)
      this.serviceLogger.debug('账号验证完成', { accountId, result })
      return result.isValid
    } catch (error) {
      this.serviceLogger.error('账号验证失败', error)
      throw error
    }
  }

  /**
   * 验证账号会话（返回详细结果）
   */
  async validateAccountWithDetails(accountId: string): Promise<{ isValid: boolean; reason?: string; details?: any }> {
    try {
      const result = await ipcService.invoke<{ isValid: boolean; reason?: string; details?: any }>('login:validate', accountId)
      this.serviceLogger.debug('账号验证完成', { accountId, result })
      return result
    } catch (error) {
      this.serviceLogger.error('账号验证失败', error)
      throw error
    }
  }

  /**
   * 删除账号
   */
  async deleteAccount(accountId: string): Promise<boolean> {
    try {
      const success = await ipcService.invoke<boolean>('login:delete-account', accountId)
      this.serviceLogger.info('删除账号', { accountId, success })
      // 清理相关缓存
      ipcService.clearCache('login:get-accounts')
      return success
    } catch (error) {
      this.serviceLogger.error('删除账号失败', error)
      throw error
    }
  }

  /**
   * 删除无效账号
   */
  async deleteInvalidAccounts(): Promise<number> {
    try {
      const deletedCount = await ipcService.invoke<number>('login:delete-invalid-accounts')
      this.serviceLogger.info('删除无效账号', { deletedCount })
      // 清理相关缓存
      ipcService.clearCache('login:get-accounts')
      return deletedCount
    } catch (error) {
      this.serviceLogger.error('删除无效账号失败', error)
      throw error
    }
  }
}

// 导出单例实例
export const accountService = new AccountService()
